package ${file.pkg_this};

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.specter.disk.poi.Excel;
import com.specter.mvc.model.Page;
import com.specter.mvc.model.Request;
import com.specter.mvc.model.dao.BaseDao;
import com.specter.utils.URLUtils;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import ${file.pkg_base}.entity.${bean.entityName};
import ${file.pkg_base}.service.${bean.entityName}Service;

/**
 * ${meta.remark!''} ${bean.tableRemark!''} 服务实现类
 *
 * @author ${meta.author!''}
 * @since ${.now?string("yyyy-MM-dd")}
 * @version 1.0
 */
@Service
public class ${file.file_name} implements ${bean.entityName}Service {

	@Autowired
	private BaseDao baseDao;

	@Override
	public ${bean.entityName} get(String id) {
		Assert.notNull(id, "Id主键不能为空！");
		return baseDao.selectOneById(${bean.entityName}.class, id);
	}

	@Override
	public Page<?> page(Request request) {
		request.asc("${bean.id.column!''}");
		request.setQueryType(Request.QueryType.PAGE);
		return baseDao.selectPage(${bean.entityName}.class, request);
	}

	@Override
	public ${bean.entityName} save(${bean.entityName} entity) {
		if (entity.getId() != null && !"".equals(entity.getId())) {
			baseDao.update(entity);
		} else {
			baseDao.insert(entity);
		}
		return entity;
	}

	@Override
	public void delete(String id) {
		baseDao.deleteById(${bean.entityName}.class, id);
	}

	@Override
	public List<?> imp(InputStream is) {
		List<${bean.entityName}> list = new ArrayList<${bean.entityName}>();
		try {
			HSSFWorkbook wb = new HSSFWorkbook(is);

			// FIXME 注意 ： 所有sheet表的数据要求一致且都含表头
			for (int i = 0; i < wb.getNumberOfSheets(); i++) {

				HSSFSheet sheet = wb.getSheetAt(i);
				// FIXME 重点注意 ： 该处循环是从 第一行开始
				for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
					HSSFRow row = sheet.getRow(rowNum);
					if (row == null)
						continue;

					// 插入 实体
					${bean.entityName} entity = new ${bean.entityName}();
					// FIXME 注意 ：1、表格数据与实体字段顺序要求一致否则自行修改 2、做好数据项校验
					<#list bean.properties as it>
					<#if it.clazz=="Integer">
					entity.set${it.name?cap_first}(Integer.valueOf(row.getCell(${it_index}).getStringCellValue()));
					<#elseif it.clazz=="Long">
					entity.set${it.name?cap_first}(Long.valueOf(row.getCell(${it_index}).getStringCellValue()));
					<#elseif it.clazz=="java.util.Date">
					entity.set${it.name?cap_first}(row.getCell(${it_index}).getDateCellValue());
					<#else>
					entity.set${it.name?cap_first}(row.getCell(${it_index}).getStringCellValue());
					</#if>
					</#list>

					list.add(entity);
				}
			}
			wb.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 插入数据前应做好错误数据分析
		baseDao.insertBatch(list);// 执行批量插入
		return list;
	}

	@Override
	public ModelAndView exp(Request request) {
		Map<String, Object> model = new HashMap<>();

		Excel xlsx = new Excel();
		<#list bean.properties as it>
		xlsx.setComment("${it.name}", "${it.remark!''}");
		</#list>

		xlsx.setHeaders(request.getString("fields").split(","));

		model.put("xlsx", xlsx);

		// 读取表数据
		List<${bean.entityName}> list = baseDao.select(${bean.entityName}.class, request.getCodex());
		model.put("list", list);

		String file = String.format("${bean.tableRemark!''}-%s.xls", DateFormatUtils.format(new Date(), "yyyyMMdd"));
		View view = new AbstractXlsView() {
			@Override
			protected void buildExcelDocument(Map<String, Object> m, Workbook wb, HttpServletRequest req, HttpServletResponse res) throws Exception {
				res.setCharacterEncoding("UTF-8");
				res.setContentType("octets/stream");
				res.setHeader("Content-Disposition", "attachment;filename=" + URLUtils.encode(file, "UTF-8"));

				((Excel) m.get("xlsx")).setWorkbook(wb, (List<?>) m.get("list"));
			}
		};

		return new ModelAndView(view, model);
	}

}
